const baseurl = "/api";

export function request<D>(
  options: Pick<Request.Options, "url" | "method" | "data" | "header">
): Promise<D> {
  const { url, method = "GET", data, header } = options;
  return new Promise((resolve, reject) => {
    uni.request({
      url: baseurl + url,
      data,
      method,
      timeout: 5000,
      header: Object.assign(header, { Token: uni.getStorageSync("token") }),
      success(response) {
        const { statusCode, data } = response;
        switch (statusCode) {
          case 200:
            resolve(data as D);
            break;
          case 401:
            uni.showModal({
              title: "提示",
              content: "请登录",
              showCancel: false,
              success() {
                uni.clearStorageSync();
                uni.navigateTo({ url: "/pages/login/login" });
              },
            });
            break;
          case 404:
            uni.showToast({ title: "资源错误", duration: 2000 });
            break;
          default:
            uni.showToast({ title: "未知错误", duration: 2000 });
            break;
        }
      },
      fail(error) {
        if (error.errMsg.indexOf("request:fail") !== -1) {
          uni.showToast({ title: "网络异常", icon: "error", duration: 2000 });
        } else {
          uni.showToast({ title: "未知异常", duration: 2000 });
        }
        reject(error);
      },
      complete() {
        uni.hideToast();
      },
    });
  });
}
